//
//  ViewController.m
//  corruptEatSerpent
//
//  Created by HYC on 2022/12/2.
//

#import "HYCEatSerpent_ViewController.h"

//#import "HYCEatSerpent_VM.h"
//#import "HYCEatSerpent_rankingListView.h"
//#import "HYCEatSerpent_eveView.h"
//#import "HYCEatSerpent_eveModel.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import <SPAlertController/SPAlertController.h>
#import <HYC_TOOLS_OC/HYC_TOOLS_OC_HEADER.h>

#import <HYC_TOOLS_OC/HYC_TOOLS_OC.h>
#import <HYC_TOOLS_OC/HYC_TOOLS_OC_HEADER.h>

#import <MultipeerConnectivity/MCAdvertiserAssistant.h>
@interface HYCEatSerpent_ViewController ()


@property (nonatomic,strong)NSMutableArray <NSMutableArray <HYCEatSerpent_eveView *>*>*bgArr;
@property (nonatomic,strong)NSMutableArray <HYCEatSerpent_eveModel *>*selfArr;
@property (nonatomic,strong)NSMutableArray <NSMutableArray <HYCEatSerpent_eveModel *>*>*allModels;
@property (nonatomic,strong)UILabel *scoreboardLabel;
@property (nonatomic,strong)UIButton *startBtn;

@property (nonatomic,strong)HYCEatSerpent_rankingListView *ranKingView;
@property (nonatomic,strong)UITextField *nameTextF;

@property (nonatomic,strong)NSMutableArray <NSDictionary *>*ranKingArr;

@property (nonatomic,strong)UILabel *CrazyMode;


//遮挡
@property (nonatomic,strong)UIView *keepOut;


@end




@implementation HYCEatSerpent_ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"首页";

    
    //添加UI
    [self addUI];
    
    //获取计分板
    [self getRanKing];
    
    [self dieBlock];
    
    [self eatFoodBlock];
    
    [self touchTwoBlock];
    
    [self addKeepOutView];
    
    
}

- (void)touchTwoBlock {
    
    [HYCEatSerpent_VM.sharedManager setTouchTwo:^(BOOL isRuned) {
            
        self.keepOut.hidden = false;
            
    }];
}

- (void)eatFoodBlock {
    
    //吃到食物
    [HYCEatSerpent_VM.sharedManager setHaveFood:^(NSInteger foodNumber) {
            
        self.scoreboardLabel.text = [NSString stringWithFormat:@"得分: %02ld 分",foodNumber];
            
    }];
    
}

- (void)dieBlock {
    
    
    WeakSelf_HYC
    
    [HYCEatSerpent_VM.sharedManager setOpenToast:^(NSInteger foods) {

        
        weakSelf.startBtn.userInteractionEnabled = true;
        weakSelf.startBtn.H_textColor(@"A2CD5A".H_color);
        
        
        if (weakSelf.ranKingArr.count < 3 || ((NSNumber *)weakSelf.ranKingArr.lastObject[@"value"]).integerValue < foods) {
            
            
            
            SPAlertController *alert = [SPAlertController alertControllerWithTitle:@"💐恭喜恭喜💐" message:@"您打破了本游戏的世界记录,请留下您的名字" preferredStyle:SPAlertControllerStyleAlert];

            SPAlertAction *action1 = [SPAlertAction actionWithTitle:@"确定" style:SPAlertActionStyleDefault handler:^(SPAlertAction * _Nonnull action) {
                
                //如果有三个元素 那就删掉最后一个
                if (weakSelf.ranKingArr.count >= 3) [weakSelf.ranKingArr removeLastObject];

                [weakSelf.ranKingArr addObject:@{@"name":self.nameTextF.text,@"value":@(foods)}];
                
                [self ranKingArr_PaiXu];
                
            }];
        
            SPAlertAction *action3 = [SPAlertAction actionWithTitle:@"取消" style:SPAlertActionStyleCancel handler:^(SPAlertAction * _Nonnull action) {}];

            [alert addAction:action1];
        
            [alert addAction:action3];
            
            [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
                    
                self.nameTextF = textField;
                    
            }];
            
            [self presentViewController: alert animated:YES completion:^{}];
            
            return;
            
            
        }else {
            SPAlertController *alert = [SPAlertController alertControllerWithTitle:@"游戏结束" message:[NSString stringWithFormat:@"得分: %ld 分",HYCEatSerpent_VM.sharedManager.foodNumber] preferredStyle:SPAlertControllerStyleAlert];
            
            SPAlertAction *action3 = [SPAlertAction actionWithTitle:@"确定" style:SPAlertActionStyleCancel handler:^(SPAlertAction * _Nonnull action) {}];
            
            [alert addAction:action3];
            [weakSelf presentViewController: alert animated:YES completion:^{}];
        }
            
        
        
        
            
    }];
}

- (void)ranKingArr_PaiXu {
    
    NSArray *sortedArray = [self.ranKingArr sortedArrayUsingComparator:^(NSDictionary * obj1,NSDictionary * obj2)
                            {
        //降序，key表示比较的关键字
        if (((NSNumber *)obj1[@"value"]).integerValue < ((NSNumber *)obj2[@"value"]).integerValue )
        {
            return NSOrderedDescending;
        }
        else
        {
            return NSOrderedAscending;
        }
    
    
}];
    
    self.ranKingArr = [NSMutableArray arrayWithArray:sortedArray];
    
    [[NSUserDefaults standardUserDefaults] setObject:self.ranKingArr forKey:@"corruptEatSerpent"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    
    [self addRanKing];
    
}


- (void)keepOutTouchTwo:(UITapGestureRecognizer *)gest {
    
    [HYCEatSerpent_VM.sharedManager touchT];
    self.keepOut.hidden = true;
    
}
- getRanKing {
    
    NSArray *arr = [[NSUserDefaults standardUserDefaults] objectForKey:@"corruptEatSerpent"];
    
    self.ranKingArr = arr.count ? [NSMutableArray arrayWithArray:arr] : [NSMutableArray arrayWithCapacity:0];

    
    [self addRanKing];
    return self;
}

- addRanKing {
    
    if (self.ranKingArr.count >= 1) {
        
        self.ranKingView.NO_1_Name.text  = self.ranKingArr[0][@"name"];
        self.ranKingView.NO_1_Value.text = ((NSNumber *)self.ranKingArr[0][@"value"]).stringValue;
    }
    if (self.ranKingArr.count >= 2) {
        
        self.ranKingView.NO_2_Name.text  = self.ranKingArr[1][@"name"];
        self.ranKingView.NO_2_Value.text  = ((NSNumber *)self.ranKingArr[1][@"value"]).stringValue;
    }
    if (self.ranKingArr.count >= 3) {
        
        self.ranKingView.NO_3_Name.text  = self.ranKingArr[2][@"name"];
        self.ranKingView.NO_3_Value.text  = ((NSNumber *)self.ranKingArr[2][@"value"]).stringValue;
    }
    
    return self;
}
- start {
    //清空所有颜色模块
    for (NSInteger i = 0; i < self.bgArr.count; i ++) for (NSInteger z = 0; z < self.bgArr[i].count; z ++) self.bgArr[i][z].colorView.backgroundColor = UIColor.whiteColor;

    self.scoreboardLabel.text = @"得分: 00 分";
    
    
    
    //添加蛇的数据
    [self addsSelf];
    
    //开始
    HYCEatSerpent_VM.sharedManager.runingType = HYC__ing;
    [HYCEatSerpent_VM.sharedManager runing:self.selfArr WithBgArr:self.bgArr];
    
    //第一次添加食物点
    [HYCEatSerpent_VM.sharedManager addFoodWithAllModels:self.allModels];
    
    //设置初始方向
    HYCEatSerpent_VM.sharedManager.fangxiang = HYC__RIGHT;
    return  self;
}

- addsSelf {
    
    self.selfArr = [NSMutableArray arrayWithCapacity:0];
    
    [self.selfArr addObject:[HYCEatSerpent_eveModel initWith_X:0 With_Y:1]];
    [self.selfArr addObject:[HYCEatSerpent_eveModel initWith_X:0 With_Y:0]];
    
    for (NSInteger i = 0; i < self.selfArr.count;  i ++) {
        
        HYCEatSerpent_eveModel *eveM = self.selfArr[i];
        self.bgArr[eveM.x][eveM.y].colorView.backgroundColor = UIColor.grayColor;
        
    }
    
    
    
    
    return self;
}


- addKeepOutView {
    WeakSelf_HYC
    self.keepOut = UIView.alloc.init;
    [self.view addSubview:self.keepOut];
    [self.keepOut mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.offset(0);
    }];
    
    UIImageView *keepOutImageView = UIImageView.alloc.init;
    
    
//    NSBundle *kZLVehicleStaticBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"HYCEatSerpent" ofType:@"bundle"]];
//    keepOutImageView.image = [UIImage imageNamed:@"HYC_EatSerpent_keepOut" inBundle:[NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"HYCEatSerpent" ofType:@"bundle"]] withConfiguration:nil ];
    
    [self.keepOut addSubview:keepOutImageView];
    [keepOutImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.offset(0);
            make.width.height.mas_equalTo(80);
    }];
    
    self.keepOut.backgroundColor = UIColor.clearColor;
    
    self.keepOut.hidden = true;
    

    
    UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(keepOutTouchTwo:)];
    tapGesture.numberOfTapsRequired=2;
    [self.keepOut addGestureRecognizer:tapGesture];
    
    
    //  _________________________________________________________________________________________________HYC_________________________________________________________________________________
    //
    UILabel *stopLabel = UILabel.alloc.init
    .H_text(@"停")
    .H_textColor(@"666666".H_color)
    .H_Font([@"180" H_weight:UIFontWeightBold]);
    
    [keepOutImageView addSubview:stopLabel];
    [stopLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.offset(0);
    }];
    
    return self;
}

/// 创建背景UI
- addUI {
    WeakSelf_HYC
    
    NSInteger eveNumber = W_Number;
    CGFloat totalLenghtWitch = SCREEN_H_WIDTH - edge * 2;
    CGFloat eveW_H = totalLenghtWitch / eveNumber;
    
    
    
    UIView *bgView = UIView.alloc.init.H_frame(CGRectMake(0, 0, SCREEN_H_WIDTH - edge * 2, H_Number * eveW_H)).H_addSubViewFoSuper(self.view);
    bgView.userInteractionEnabled = false;
    [HYCEatSerpent_VM.sharedManager addGestSwipe:self.view];
    [HYCEatSerpent_VM.sharedManager addGestLongTouch:self.view];

    bgView.center = self.view.center;

    self.bgArr = [NSMutableArray arrayWithCapacity:0];
    self.allModels = [NSMutableArray arrayWithCapacity:0];
    
    for (NSInteger y = 0; y < H_Number; y ++) {
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
        NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:0];
        for (NSInteger x = 0; x < eveNumber; x ++) {
            HYCEatSerpent_eveView *eveV = HYCEatSerpent_eveView.alloc.init;
            eveV.userInteractionEnabled = false;
            [bgView addSubview:eveV];
            eveV.frame = CGRectMake(x *eveW_H, y *eveW_H, eveW_H, eveW_H);
            [arr addObject:eveV];
            [arrM addObject:[HYCEatSerpent_eveModel initWith_X:y With_Y:x]];
            
            
        }
        
        [self.bgArr addObject:arr];
        [self.allModels addObject:arrM];
    }
    
    
    self.scoreboardLabel = UILabel.alloc.init
    .H_text(@"得分: 00 分")
    .H_Font(@"25".H_font)
    .H_addSubViewFoSuper(self.view);
    [self.scoreboardLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(bgView.mas_top).offset(-SCREEN_H_DISTANCE(30));
        make.centerX.offset(0);
    }];
    
    
    
    self.startBtn = UIButton.alloc.init
        .H_text(@"开始")
        .H_Font(@"25".H_font)
        .H_textColor(@"A2CD5A".H_color)
        .H_addSubViewFoSuper(self.view);
    [self.startBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.scoreboardLabel.mas_top).offset(-SCREEN_H_DISTANCE(30));
            make.centerX.offset(0);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(30);
    }];
    
    [self.startBtn addGuest:tapAction resutlBlock:^(UITapGestureRecognizer * _Nonnull gesture) {
            
            
        [weakSelf start];
        weakSelf.startBtn.userInteractionEnabled = false;
        weakSelf.startBtn.H_textColor(UIColor.groupTableViewBackgroundColor);
    }];
    
    
    //  _________________________________________________________________________________________________HYC_________________________________________________________________________________
    //
    self.CrazyMode = UILabel.alloc.init
    .H_text(@"疯狂模式")
    .H_textColor(@"C43C3C".H_color)
    .H_Font(@"30".H_font)
    .H_addSubViewFoSuper(self.view);
    
    [self.CrazyMode mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.startBtn).offset(0);
            make.left.equalTo(self.startBtn.mas_right).offset(20);
    }];
    
    
    [self.CrazyMode addGuest:tapAction resutlBlock:^(UITapGestureRecognizer * _Nonnull gesture) {
            
        if ([weakSelf.CrazyMode.text isEqualToString:@"疯狂模式"]) {
            
            weakSelf.CrazyMode.text = @"普通模式";
            
            HYCEatSerpent_VM.sharedManager.isCrazyMode = true;
            
        }else {
            
            weakSelf.CrazyMode.text = @"疯狂模式";
            
            HYCEatSerpent_VM.sharedManager.isCrazyMode = false;
        }
            
    }];
    
    
    
    
    //  _________________________________________________________________________________________________HYC_________________________________________________________________________________
    //
    self.ranKingView = HYCEatSerpent_rankingListView.alloc.init.H_addSubViewFoSuper(self.view);
    
    self.ranKingView.frame = CGRectMake(10, 10, 100, 300);

    
    
    
    
    
    
    
    
    return self;
}

@end




